import RightFixed from '@/layouts/RightFixed';
import TopBread from '@/layouts/TopBread';
import { selectSaleById } from '@/services/business';
import { selectGoods } from '@/services/commodity';
import { addShopCar } from '@/services/shopCar';
import { colorStr, getQueryParams } from '@/utils/utils';
import { BackTop, Button, InputNumber, Menu, message } from 'antd';
import 'emoji-regex';
import { useCallback, useEffect, useState } from 'react';
import { history } from 'umi';
import AddressConfirm from './components/AddressConfirm';
import GoodsAppraise from './components/GoodsAppraise';
import GoodsInfor from './components/GoodsInfor';
import styles from './index.less';

const Commodity: React.FC = () => {
  const qs = getQueryParams();
  const { id, lastRoute }: any = history?.location?.query;
  // 主题颜色的值
  const [color, setColor] = useState<string>(localStorage.getItem('color') || '#1a7721');
  // 当前查看的图片的key
  const [imgKey, setImgKey] = useState<number>(1);
  // const [visible, setVisible] = useState(false);
  const [menuKey, setMenuKey] = useState('0');
  // 数量的值
  const [qtyValue, setQtyValue] = useState<number>(1);
  const [addressModal, setAddressModal] = useState<boolean>(false);
  const [goods, setGoods] = useState<any>({});
  const [sale, setSale] = useState<any>({});
  const [imgsList, setImgsList] = useState<any[]>([]);

  const selectBusiness = useCallback(async (saleid: any) => {
    try {
      await selectSaleById({ id: saleid }).then((res) => {
        setSale(res);
      });
    } catch (error) {
      console.log(error);
    }
  }, []);

  const addCar = async () => {
    try {
      await addShopCar({ userId: qs.id, commodityId: goods.id, qty: qtyValue }).then((res) => {
        if (res === '1') {
          message.error('该商品库存不足，加购失败！');
        } else {
          message.success('加入购物车成功！');
        }
      });
    } catch (error) {
      console.log(error);
    }
  };

  const selectById = useCallback(async () => {
    try {
      await selectGoods({ id: id }).then((res) => {
        setGoods(res);
        selectBusiness(res.companyid);
        let current = JSON.stringify(res.img)
          .replace('[', '')
          .replace(']', '')
          .replace(/"/g, '')
          .replace(/\\/g, '')
          .split(',');
        let arr: any[] = [];
        current.map((item: string, index: number) => {
          arr.push({ key: index + 1, url: item });
        });
        setImgsList(arr);
      });
    } catch (error) {
      console.log(error);
    }
  }, [id, selectBusiness]);

  useEffect(() => {
    selectById();
  }, [selectById]);

  const style: React.CSSProperties = {
    height: 59,
    width: 63,
    lineHeight: '40px',
    borderRadius: 17,
    backgroundColor: color,
    color: '#fff',
    textAlign: 'center',
    fontSize: 14,
  };

  // 切换商品详情/商品评价
  const menuChange = (e: any) => {
    setMenuKey(e.key);
  };

  const goodsQtyChange = (value: any) => {
    setQtyValue(value);
  };

  const btnAdd: React.CSSProperties = {
    background: colorStr(2),
    color: color,
    borderRadius: '18px 0',
  };

  return (
    <div className={styles.container}>
      <TopBread lastRoute={lastRoute} now={'商品详情'} setColorParent={setColor} />
      <div className={styles.contentStyle}>
        <div className={styles.content}>
          <div className={styles.images}>
            <div className={styles.nextBtnl}>
              {imgKey > 1 && (
                <img
                  src={require('@/assets/images/向左.svg')}
                  alt={'加载失败'}
                  className={styles.nextBtnl}
                  style={{
                    cursor: 'pointer',
                  }}
                  onClick={() => {
                    setImgKey(imgKey - 1);
                  }}
                />
              )}
            </div>
            <div>
              {imgsList.map((item: any) => {
                if (imgKey === item.key) {
                  return (
                    <img
                      key={item.key}
                      src={`http://localhost:8090/dyh/upload_images/commodity/${item.url}`}
                      style={{ marginBottom: 20 }}
                      alt={'dsf'}
                      className={styles.goodsImgs}
                    />
                  );
                } else {
                  return <div key={item.key} />;
                }
              })}
            </div>
            <div className={styles.nextBtn}>
              {imgsList.map((item: any) => {
                if (imgKey === item.key - 1) {
                  return (
                    <img
                      key={item.key}
                      src={require('@/assets/images/向右.svg')}
                      alt={'加载失败'}
                      className={styles.nextBtn}
                      style={{
                        cursor: 'pointer',
                        marginLeft: 10,
                      }}
                      onClick={() => {
                        setImgKey(imgKey + 1);
                      }}
                    />
                  );
                } else {
                  return <div key={item.key} />;
                }
              })}
            </div>
          </div>
          <div className={styles.goods}>
            <div className={styles.goodsTitle}>
              {goods?.ispush !== '0' && (
                <div className={styles.ifPush} style={{ backgroundColor: color }}>
                  官方推荐
                </div>
              )}
              <div className={styles.titleText}>
                <span>&nbsp; </span>
                {goods.title}
              </div>
            </div>
            <div
              className={styles.goodsSale}
              style={{
                background: colorStr(6),
              }}
            >
              <div className={styles.money}>
                <span className={styles.leftText}>价格</span>
                <span className={styles.rightMoney}>¥{goods?.price}</span>
              </div>
              <div className={styles.sold}>
                <span className={styles.leftText}>月销量</span>
                <span>{`${goods?.month}`} 件</span>
              </div>
            </div>
            <div className={styles.goodsAddress}>
              <span className={styles.leftText}> 发货地址</span>
              <span> {`${sale?.province}  ${sale?.city}  ${sale?.area}`}</span>
            </div>
            <div className={styles.goodsQty}>
              <span className={styles.leftText}>数&emsp;量：&emsp;</span>
              <InputNumber min={1} defaultValue={1} onChange={goodsQtyChange} />
              <span className={styles.havaGoods}>库存：({goods.stock})</span>
            </div>
            {qs.role !== '3' && (
              <div className={styles.goodsBtns}>
                <Button
                  className={styles.addCar}
                  style={btnAdd}
                  onClick={() => {
                    if (goods.stock >= qtyValue) {
                      addCar();
                    } else {
                      message.error('该商品库存不足，加购失败！');
                    }
                  }}
                >
                  加入购物车
                </Button>
                <Button
                  className={styles.addBuy}
                  style={btnAdd}
                  onClick={() => {
                    if (goods.stock >= qtyValue) {
                      setAddressModal(true);
                    } else {
                      message.error('该商品库存不足，购买失败！');
                    }
                  }}
                >
                  立即购买
                </Button>
              </div>
            )}
          </div>
        </div>
        <div className={styles.line} />
        <div className={styles.otherContent}>
          <Menu
            mode="horizontal"
            className={styles.menuStyle}
            onClick={menuChange}
            style={{
              background: colorStr(6),
              borderRadius: '18px 18px 0 0',
              border: 0,
              height: 58,
              fontSize: 18,
              padding: '4px 41px',
            }}
            defaultSelectedKeys={[menuKey]}
          >
            <Menu.Item key={'0'}>商品详情</Menu.Item>
            <Menu.Item key={'1'}>商品评价</Menu.Item>
          </Menu>
          {menuKey === '0' && (
            <GoodsInfor color={color} business={sale} goodsDetail={goods.detail} />
          )}
          {menuKey === '1' && <GoodsAppraise color={color} goodsid={goods.id} />}
        </div>
      </div>
      <RightFixed color={color} thisRoute={'商品详情'} />
      <BackTop>
        <div style={style}>
          <div className={styles.upBtnBox}>
            <img
              src={require('@/assets/images/回顶部.svg')}
              alt={'加载失败'}
              className={styles.upBtn}
            />
          </div>
          <div>回顶部</div>
        </div>
      </BackTop>
      <AddressConfirm
        visible={addressModal}
        onCancel={() => {
          setAddressModal(false);
        }}
        goods={goods}
        selectById={selectById}
        qtyValue={qtyValue}
      />
    </div>
  );
};

export default Commodity;
